﻿using System;
using NguyenHoa.Web.App_Code;
using NguyenHoa.Domains;
using NguyenHoa.Services;
using System.IO;
using DevExpress.Web.ASPxDataView;
using System.Web.UI.HtmlControls;

namespace NguyenHoa.Web.Pages
{
  public partial class PromotionsPage : BasePage
  {
    #region Properties
    private int PromotionsLimit = 10;
    #endregion

    #region Events

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      {
        LoadNews();
      }

      if (dvNews.IsCallback)
      {
        LoadNews();
      }
    }

    protected void dvNews_DataBound(object sender, EventArgs e)
    {
      foreach (DataViewItem item in dvNews.Items)
      {
        HtmlGenericControl div = dvNews.FindItemControl("divImage", item) as HtmlGenericControl;
        if (div != null)
        {
          Domains.News news = item.DataItem as Domains.News;
          if (news != null && !string.IsNullOrEmpty(news.ImagePath))
          {
            div.Attributes.Add("style", "display:''");
            continue;
          }
          div.Attributes.Add("style", "display:none");
        }
      }
    }
    #endregion

    #region Methods

    private void LoadNews()
    {
      TList<Domains.News> newsList = new NewsService().GetByHomeSearch(null, CurrentLanguage.Id, TypeId, null, "P");

      foreach (Domains.News news in newsList)
      {
        if (news.ViewCount == null)
          news.ViewCount = 0;
        if (!string.IsNullOrEmpty(news.ImagePath))
        {
          if (File.Exists(MapPath("../" + news.ImagePath)))
          {
            news.ImagePath = "../" + news.ImagePath;
          }
        }
      }

      dvNews.DataSource = TypeId == 0 ? newsList.GetRange(0, PromotionsLimit) : newsList;
      dvNews.DataBind();
    }

    public string FormatDate(object value)
    {
      return Utils.FormatDate(value);
    }
    #endregion
  }
}
